<template>
  <div>
    <div class="main">
      <div class="overview">班级平均年龄：{{ avgAge }}</div>

      <headeradd
        @isShowstudentModal="isShowstudentModal"
        @removeCheck="removeCheck"
        :keyword="keyword"
        @sousuo="sousuo"
      ></headeradd>

      <table class="studentTable">
        <thead>
          <tr>
            <th>
              <input
                type="checkbox"
                v-model="checkedAll"
                class="selectAll"
                @change="togcheckedAll"
              />
            </th>
            <th>ID</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Hobbies</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Age</th>
            <th>Created At</th>
            <th>Updated At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <!-- Student rows will be added dynamically here -->
          <tr v-for="item in studentarr2" :key="item.id">
            <td><input type="checkbox" v-model="item.checkedlist" /></td>
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.gender }}</td>
            <td>{{ item.hobbies }}</td>
            <td>{{ item.email }}</td>
            <td>{{ item.phone }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.create_at }}</td>
            <td>{{ item.update_at }}</td>
            <td>
              <button @click="removeDate(item.id)" class="editBtn">删除</button>
              <button @click="repusDate(item)" class="deleteBtn">修改</button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- Modal for adding/editing students -->

      <div class="studentModal modal" v-show="openModalBtn" @click="closeModel">
        <div class="modal-content" @click.stop>
          <h3 class="modalTitle">{{ peizi.title }}</h3>
          <addStudy @saveStuInfo="saveStuInfo" :userInfo="stuForData" ref="datains" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import addStudy from './addStudy.vue'
import headeradd from './headeradd.vue'
import { computed, ref, watch, useTemplateRef } from 'vue'
// import { reactive } from 'vue'
import { getNowDateTime } from '@/utils/index'
import { uniqueId } from 'lodash'
import { type IStudent } from './addStudy.vue'

// import _ from 'lodash'
// import { generateUUID } from '@/utils/index'

// const uniqueId: any = ref(_.uniqueId())

// let unid = computed(() => {
//   return uniqueId.value + 1
// })

const datains = useTemplateRef('datains')

// 配置状态
const peizi = ref({
  type: 'add',
  title: '添加学生信息'
})

let student = ref<Array<IStudent>>([
  {
    id: 1,
    name: 'Alice',
    gender: 'Female',
    hobbies: 'Reading',
    email: 'alice@example.com',
    phone: '12345678901',
    age: 20,
    create_at: getNowDateTime(),
    update_at: getNowDateTime(),
    checkedlist: false
  },
  {
    id: 2,
    name: 'Bob',
    gender: 'Male',
    hobbies: 'Sports',
    email: 'bob@example.com',
    phone: '10987654321',
    age: 22,
    create_at: getNowDateTime(),
    update_at: getNowDateTime(),
    checkedlist: false
  }
])

function initActive() {
  // 取数据
  logstudata()
  // 存数据
  shujucunchu()

  sousuo()
}

// 重置变量（初始）
const studentarr2 = ref<Array<IStudent>>([])

// 搜索按钮
let keyword = ref('')

function sousuo() {
  studentarr2.value = student.value.filter((item) => item.name.includes(keyword.value))
}

const stuForData = ref<IStudent>({
  id: '',
  name: '',
  gender: '',
  hobbies: '',
  email: '',
  phone: '',
  age: 0,
  checkedlist: false
})

const saveStuInfo = (Studentzi: IStudent) => {
  // 判断是添加还是修改
  stuForData.value = Studentzi
  if (peizi.value.type === 'add') {
    //添加学生信息
    //1.生成学生id
    // console.log(stuForData.value)
    // console.log(Studentzi)

    // getuuid()
    stuForData.value.id = uniqueId()

    student.value.push({
      ...JSON.parse(JSON.stringify(stuForData.value)),
      create_at: getNowDateTime(),
      update_at: getNowDateTime()
    })
  } else {
    console.log(stuForData.value, '修改学生信息')
    let { id, name, gender, hobbies, email, phone, age } = stuForData.value

    student.value.find((item) => {
      if (item.id === id) {
        item.name = name
        item.gender = gender
        item.hobbies = hobbies
        item.email = email
        item.phone = phone
        item.age = age as number
        item.update_at = getNowDateTime()
      }
    })
  }
  sousuo()
  shujucunchu()
  openModalBtn.value = false
}

// 修改学生信息
function repusDate(str: IStudent) {
  peizi.value.type = 'adit'
  peizi.value.title = '修改学生信息'
  openModalBtn.value = true
  sousuo()
  datains.value?.stu(JSON.parse(JSON.stringify(str)))
  // console.log(stuForData.value)
}

// 默认关闭模态框
let openModalBtn = ref(false)

// 添加学生信息
function isShowstudentModal() {
  datains.value?.setteData()
  // stuForData.value = {
  //   id: '',
  //   name: '',
  //   gender: '',
  //   hobbies: '',
  //   email: '',
  //   phone: '',
  //   age: 0
  // }
  peizi.value.type = 'add'
  peizi.value.title = '添加学生信息'
  openModalBtn.value = true
  sousuo()
  shujucunchu()
}

// 平均年龄
const avgAge = computed(() => {
  return (
    Math.floor(
      studentarr2.value.reduce(
        (perciousValue, currenValue) => (perciousValue = perciousValue + Number(currenValue.age)),
        0
      ) / studentarr2.value.length
    ) || 0
  )
})

// 删除成员
// function removeDate(id: string | number) {
//   student = student.filter((items) => items.id !== id)
// }
function removeDate(id: string | number) {
  const index = studentarr2.value.findIndex((items) => items.id === id)
  if (index !== -1) {
    studentarr2.value.splice(index, 1)
  }
  student.value = studentarr2.value
  shujucunchu()
}

// 全选框
const checkedAll = ref(false)
function togcheckedAll() {
  studentarr2.value.forEach((item) => {
    item.checkedlist = checkedAll.value
  })
}

// 监听复选框
watch(
  () => studentarr2.value.every((item) => item.checkedlist),
  (newVal) => {
    checkedAll.value = newVal
  }
)
// 点击关闭模态框
function closeModel() {
  openModalBtn.value = false
}
// // 选中删除
function removeCheck() {
  studentarr2.value = studentarr2.value.filter((items) => !items.checkedlist)
  // console.log(...arrstu)
  // splice（ 从第0个开始，删除多少个，替换的数据）
  // studentarr2.value.splice(0, student.value.length, ...arrstu)
  student.value = student.value.filter((item) => !item.checkedlist)

  checkedAll.value = false
  shujucunchu()
}

// const removeCheck = () => {
//   // 过滤掉选中的学生
//   studentarr2.value = studentarr2.value.filter((item: IStudent) => !item.checkedlist) // 从原始数据中删除这些学生
//   student.value = student.value.filter((item: IStudent) => !item.checkedlist) // 重置选中状态
//   checkedAll.value = false
// }

function logstudata() {
  let studata = localStorage.getItem('stu')
  if (studata) {
    student.value = JSON.parse(studata)
  }
}

function shujucunchu() {
  localStorage.setItem('stu', JSON.stringify(student.value))
}

// 初始化数据
initActive()
</script>

<style lang="scss" scoped>
@import './style/demo1.scss';
</style>
